/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.grant.permgroup.impl;

import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.TreeUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.model.dd.DicInfoVo;
import com.je.rbac.exception.PermGroupException;
import com.je.rbac.service.grant.permgroup.RbacGrantPermGroupService;
import com.je.rbac.service.permission.PermissionLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("rbacGrantPermGroupService")
public class RbacGrantPermGroupServiceImpl implements RbacGrantPermGroupService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private PermissionLoadService permissionLoadService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void insertPermGroup(String name) {
        int count = 0;
        List<Map<String,Object>> countList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_PERMGROUP");
        if(countList.size()>0){
            count = (int) countList.get(0).get("MAX_COUNT");
        }
        DynaBean permGroupBean = new DynaBean("JE_RBAC_PERMGROUP", false);
        permGroupBean.set("PERMGROUP_NAME", name);
        permGroupBean.set("PERMGROUP_CODE", "permGroup-" + String.format("%06d", count + 1));
        permGroupBean.set("SY_ORDERINDEX", count + 1);
        commonService.buildModelCreateInfo(permGroupBean);
        metaService.insert(permGroupBean);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updatePermGroup(String id, String name) throws PermGroupException {
        DynaBean permGroupBean = metaService.selectOne("JE_RBAC_PERMGROUP", ConditionsWrapper.builder()
                .eq("JE_RBAC_PERMGROUP_ID", id));
        if (permGroupBean == null) {
            throw new PermGroupException("不存在此权限组！");
        }
        permGroupBean.set("PERMGROUP_NAME", name);
        metaService.update(permGroupBean);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void move(String id, int targetIndex) {
        List<DynaBean> beanList = metaService.select("JE_RBAC_PERMGROUP", ConditionsWrapper.builder().orderByAsc("SY_ORDERINDEX"));
        List<DynaBean> sortedList = new ArrayList<>();
        DynaBean mainBean = null;
        for (int i = 0; i < beanList.size(); i++) {
            if (beanList.get(i).getStr("JE_RBAC_PERMGROUP_ID").equals(id)) {
                mainBean = beanList.get(i);
            } else {
                sortedList.add(beanList.get(i));
            }
        }
        if(mainBean == null){
            return;
        }
        sortedList.add(targetIndex,mainBean);
        for (int i = 0; i < sortedList.size(); i++) {
            if(!String.valueOf(i+1).equals(sortedList.get(i).getStr("SY_ORDERINDEX"))){
                metaService.executeSql("UPDATE JE_RBAC_PERMGROUP SET SY_ORDERINDEX = {0} WHERE JE_RBAC_PERMGROUP_ID = {1}",
                        i+1,sortedList.get(i).getStr("JE_RBAC_PERMGROUP_ID"));
            }
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void removePermGroup(String id) throws PermGroupException {
        DynaBean permGroupBean = metaService.selectOne("JE_RBAC_PERMGROUP", ConditionsWrapper.builder()
                .eq("JE_RBAC_PERMGROUP_ID", id));
        if (permGroupBean == null) {
            throw new PermGroupException("不存在此权限组！");
        }
        metaService.delete("JE_RBAC_PERMGROUP", ConditionsWrapper.builder().eq("JE_RBAC_PERMGROUP_ID", id));
    }

    @Override
    public JSONTreeNode buildPermGroupTree(DicInfoVo dicInfoVo) {
        JSONTreeNode rootNode = TreeUtil.buildRootNode();
        List<DynaBean> beanList = metaService.select("JE_RBAC_PERMGROUP", ConditionsWrapper.builder().orderByAsc("SY_ORDERINDEX"));
        JSONTreeNode eachNode;
        for (DynaBean eachPermGroup : beanList) {
            eachNode = new JSONTreeNode();
            eachNode.setText(eachPermGroup.getStr("PERMGROUP_NAME"));
            eachNode.setCode(eachPermGroup.getStr("PERMGROUP_CODE"));
            eachNode.setChecked(false);
            eachNode.setIcon("fal fa-user-friends");
            eachNode.setNodeType("LEAF");
            eachNode.setLeaf(true);
            eachNode.setLayer("1");
            eachNode.setParent("ROOT");
            eachNode.setNodeInfoType("org");
            eachNode.setNodeInfo(eachPermGroup.getStr("PERMGROUP_CODE"));
            eachNode.setId(eachPermGroup.getStr("JE_RBAC_PERMGROUP_ID"));
            eachNode.setBean(eachPermGroup.getValues());
            eachNode.setExpanded(true);
            rootNode.getChildren().add(eachNode);
        }
        return rootNode;
    }
}
